package com.mdd.front.service.impl;

import com.alibaba.excel.util.BeanMapUtils;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.*;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.yulichang.query.MPJQueryWrapper;
import com.mdd.common.core.PageResult;
import com.mdd.common.entity.competition.*;
import com.mdd.common.entity.member.Member;
import com.mdd.common.enums.YesNoEnum;
import com.mdd.common.exception.BaseException;
import com.mdd.common.mapper.competition.*;
import com.mdd.common.mapper.member.MemberMapper;
import com.mdd.common.mapper.user.UserMapper;
import com.mdd.common.util.TimeUtils;
import com.mdd.front.service.ICompetitionService;
import com.mdd.front.validate.common.PageValidate;
import com.mdd.front.validate.competition.*;
import com.mdd.front.vo.competition.*;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.lang.reflect.Field;
import java.util.*;

@Service
public class CompetitionServiceImpl implements ICompetitionService {

    @Resource
    CompetitionMapper competitionMapper;

    @Resource
    CompetitionMatchMapper competitionMatchMapper;

    @Resource
    CompetitionDetailMapper competitionDetailMapper;

    @Resource
    CompetitionAttachmentMapper competitionAttachmentMapper;

    @Resource
    CompetitionApplyMapper competitionApplyMapper;

    @Resource
    UserMapper userMapper;
    @Resource
    MemberMapper memberMapper;

    @Resource
    CompetitionSiteMapper competitionSiteMapper;

    @Resource
    CompetitionScoreMapper competitionScoreMapper;
    @Resource
    CompetitionRuleMapper competitionRuleMapper;

    @Resource
    CompetitionMatchDetailMapper competitionMatchDetailMapper;
    @Resource
    CompetitionMatchTeamMapper competitionMatchTeamMapper;

    /**
     * 赛事列列表
     *
     * @author LikeAdmin
     * @param pageValidate 分页参数
     * @param searchValidate 搜索参数
     * @return PageResult<CompetitionListedVo>
     */
    @Override
    public PageResult<CompetitionListedVo> list(PageValidate pageValidate, CompetitionSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        QueryWrapper<Competition> queryWrapper = new QueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(searchValidate.getKeyword()),"name",searchValidate.getKeyword());
        queryWrapper.eq("status",1);
        queryWrapper.orderByDesc("id");

        competitionMapper.setSearch(queryWrapper, searchValidate, new String[]{
                "like:name:str",
                "=:cover:str",
                "=:address:str",
                "=:playTime@play_time:str",
                "like:playType@play_type:str",
                "=:schedule:str",
                "=:status:int",
                "=:orgParty@org_party:str",
                "=:orgId@org_id:long",
                "=:createId@create_id:int",
                "=:updateId@update_id:int",
        });

        IPage<Competition> iPage = competitionMapper.selectPage(new Page<>(page, limit), queryWrapper);

        List<CompetitionListedVo> list = new LinkedList<>();
        for(Competition item : iPage.getRecords()) {
            CompetitionListedVo vo = new CompetitionListedVo();
            BeanUtils.copyProperties(item, vo);
            vo.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            vo.setUpdateTime(TimeUtils.timestampToDate(item.getUpdateTime()));
            list.add(vo);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public CompetitionDetailVo detail(Integer id, Integer userId) {
        Competition article = competitionMapper.selectOne(new QueryWrapper<Competition>()
                .eq("id", id)
                .eq("status", YesNoEnum.YES.getCode())
                .last("limit 1"));

        Assert.notNull(article, "数据不存在!");

        CompetitionDetail articleCollect = competitionDetailMapper.selectOne(new QueryWrapper<CompetitionDetail>()
                .eq("competition_id", article.getId())
                .last("limit 1"));

        List<CompetitionAttachment> competitionAttachmentList = competitionAttachmentMapper.selectList(new QueryWrapper<CompetitionAttachment>()
                .eq("competition_id", article.getId()));

        CompetitionDetailVo vo = new CompetitionDetailVo();
        BeanUtils.copyProperties(article, vo);
        if(articleCollect!=null) {
            vo.setContent(articleCollect.getContent());
        }
        vo.setCompetitionAttachmentList(competitionAttachmentList);
        vo.setCreateTime(TimeUtils.timestampToDate(article.getCreateTime()));
        vo.setUpdateTime(TimeUtils.timestampToDate(article.getUpdateTime()));

        article.setViewNum(article.getViewNum() + 1);
        competitionMapper.updateById(article);

        return vo;
    }

    @Override
    public void apply(CompetitionApplyValidate competitionApplyValidate) {
        if(StringUtils.isNotEmpty(competitionApplyValidate.getNanOne())){
            if("1".equals(competitionApplyValidate.getNanOne())){
                CompetitionApply competitionApply = new CompetitionApply();
                competitionApply.setCompetitionId(competitionApplyValidate.getCompetitionId());
                competitionApply.setMemberId(competitionApplyValidate.getMemberId());
                competitionApply.setApplyType(1);
                competitionApply.setStatus(1);
                competitionApply.setTeamNo(IdWorker.getIdStr());
                competitionApply.setCreateTime(System.currentTimeMillis() / 1000);
                boolean exists = competitionApplyMapper.exists(new LambdaQueryWrapper<CompetitionApply>()
                        .eq(CompetitionApply::getCompetitionId, competitionApply.getCompetitionId())
                        .eq(CompetitionApply::getApplyType, 1)
                        .eq(CompetitionApply::getMemberId,competitionApply.getMemberId()));
                if(!exists) {
                    competitionApplyMapper.insert(competitionApply);
                }
            }
        }

        if(StringUtils.isNotEmpty(competitionApplyValidate.getNanTwo())){
            if("1".equals(competitionApplyValidate.getNanTwo())){
                CompetitionApply competitionApply = new CompetitionApply();
                competitionApply.setCompetitionId(competitionApplyValidate.getCompetitionId());
                competitionApply.setMemberId(competitionApplyValidate.getMemberId());
                competitionApply.setApplyType(2);
                competitionApply.setStatus(0);
                competitionApply.setTeamNo(IdWorker.getIdStr());
                competitionApply.setCreateTime(System.currentTimeMillis() / 1000);
                boolean exists = competitionApplyMapper.exists(new LambdaQueryWrapper<CompetitionApply>()
                        .eq(CompetitionApply::getCompetitionId, competitionApply.getCompetitionId())
                        .eq(CompetitionApply::getApplyType, 2)
                        .eq(CompetitionApply::getMemberId,competitionApply.getMemberId()));
                if(!exists) {
                    competitionApplyMapper.insert(competitionApply);
                }
            }
        }

        if(StringUtils.isNotEmpty(competitionApplyValidate.getNvOne())){
            if("1".equals(competitionApplyValidate.getNvOne())){
                CompetitionApply competitionApply = new CompetitionApply();
                competitionApply.setCompetitionId(competitionApplyValidate.getCompetitionId());
                competitionApply.setMemberId(competitionApplyValidate.getMemberId());
                competitionApply.setApplyType(3);
                competitionApply.setStatus(1);
                competitionApply.setTeamNo(IdWorker.getIdStr());
                competitionApply.setCreateTime(System.currentTimeMillis() / 1000);
                boolean exists = competitionApplyMapper.exists(new LambdaQueryWrapper<CompetitionApply>()
                        .eq(CompetitionApply::getCompetitionId, competitionApply.getCompetitionId())
                        .eq(CompetitionApply::getApplyType, 3)
                        .eq(CompetitionApply::getMemberId,competitionApply.getMemberId()));
                if(!exists) {
                    competitionApplyMapper.insert(competitionApply);
                }
            }
        }

        if(StringUtils.isNotEmpty(competitionApplyValidate.getNvTwo())){
            if("1".equals(competitionApplyValidate.getNvTwo())){
                CompetitionApply competitionApply = new CompetitionApply();
                competitionApply.setCompetitionId(competitionApplyValidate.getCompetitionId());
                competitionApply.setMemberId(competitionApplyValidate.getMemberId());
                competitionApply.setApplyType(4);
                competitionApply.setStatus(0);
                competitionApply.setTeamNo(IdWorker.getIdStr());
                competitionApply.setCreateTime(System.currentTimeMillis() / 1000);
                boolean exists = competitionApplyMapper.exists(new LambdaQueryWrapper<CompetitionApply>()
                        .eq(CompetitionApply::getCompetitionId, competitionApply.getCompetitionId())
                        .eq(CompetitionApply::getApplyType, 4)
                        .eq(CompetitionApply::getMemberId,competitionApply.getMemberId()));
                if(!exists) {
                    competitionApplyMapper.insert(competitionApply);
                }
            }
        }

        if(StringUtils.isNotEmpty(competitionApplyValidate.getAllTwo())){
            if("1".equals(competitionApplyValidate.getAllTwo())){
                CompetitionApply competitionApply = new CompetitionApply();
                competitionApply.setCompetitionId(competitionApplyValidate.getCompetitionId());
                competitionApply.setMemberId(competitionApplyValidate.getMemberId());
                competitionApply.setApplyType(5);
                competitionApply.setStatus(0);
                competitionApply.setTeamNo(IdWorker.getIdStr());
                competitionApply.setCreateTime(System.currentTimeMillis() / 1000);
                boolean exists = competitionApplyMapper.exists(new LambdaQueryWrapper<CompetitionApply>()
                        .eq(CompetitionApply::getCompetitionId, competitionApply.getCompetitionId())
                        .eq(CompetitionApply::getApplyType, 5)
                        .eq(CompetitionApply::getMemberId,competitionApply.getMemberId()));
                if(!exists) {
                    competitionApplyMapper.insert(competitionApply);
                }
            }
        }
    }

    @Override
    public PageResult<CompetitionApplyListsVo> applyLists(Integer memberId,PageValidate pageValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();

        MPJQueryWrapper<CompetitionApply> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper.selectAll(CompetitionApply.class)
                .select("lc.name,lc.cover,lc.description,lc.registration_time,lc.registration_end_time,lc.org_party")
                .innerJoin("la_competition lc on lc.id = t.competition_id")
                .orderByDesc("id");
        Map<String,Object> param = new HashMap<>();

        param.put("memberId",memberId);
//        param.put("schedule", Arrays.asList(0,1));

        competitionApplyMapper.setSearch(queryWrapper, param, new String[]{
                "=:memberId@member_id:int"
        });
        IPage<CompetitionApplyListsVo> iPage = competitionApplyMapper.selectJoinPage(new Page<>(page, limit),
                CompetitionApplyListsVo.class,
                queryWrapper);

        List<CompetitionApplyListsVo> list = new LinkedList<>();
        for(CompetitionApplyListsVo item : iPage.getRecords()) {
            item.setCreateTime(TimeUtils.timestampToDate(item.getCreateTime()));
            list.add(item);
        }

        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), list);
    }

    @Override
    public void applyCancel(Integer articleId) {
        CompetitionApply competitionApply = competitionApplyMapper.selectById(articleId);
        if(ObjectUtils.isNotEmpty(competitionApply)){
            if(competitionApply.getStatus()==0) {
                CompetitionApply competitionApply1 = new CompetitionApply();
                competitionApply1.setId(competitionApply.getId());
                competitionApply1.setStatus(2);
                competitionApplyMapper.updateById(competitionApply1);
            }else{
                throw new BaseException(0,"该报名已经成功！",1);
            }
        }
    }

    @Override
    public CompetitionApplyInviteVo applyInvite(String code) {
        List<CompetitionApply> competitionApply = competitionApplyMapper.selectList(new LambdaQueryWrapper<CompetitionApply>().eq(CompetitionApply::getTeamNo,code));
        if(CollectionUtils.isNotEmpty(competitionApply)){
            MPJQueryWrapper<CompetitionApply> queryWrapper = new MPJQueryWrapper<>();
            queryWrapper.selectAll(CompetitionApply.class)
                    .select("lc.name,lc.cover,lc.description,lc.registration_time,lc.registration_end_time, lc.org_party,lu.name as inviteName,lu.sex")
                    .innerJoin("la_competition lc on lc.id = t.competition_id")
                    .innerJoin("la_member lu on lu.id = t.member_id")
                    .orderByDesc("id");
            Map<String,Object> param = new HashMap<>();

            param.put("id",competitionApply.get(0).getId());
            param.put("status", Arrays.asList("0", "1"));

            competitionApplyMapper.setSearch(queryWrapper, param, new String[]{
                    "=:id@t.id:int"
            });
            CompetitionApplyInviteVo invite = competitionApplyMapper.selectJoinOne(
                    CompetitionApplyInviteVo.class,
                    queryWrapper);
            return invite;
        }
        return null;
    }

    @Override
    public void applyAccept(CompetitionApplyAcceptValidate applyAcceptValidate) {
        List<CompetitionApply> competitionApplies = competitionApplyMapper.selectList(new LambdaQueryWrapper<CompetitionApply>()
                .ne(CompetitionApply::getMemberId,applyAcceptValidate.getMemberId())
                .eq(CompetitionApply::getTeamNo, applyAcceptValidate.getTeamNo()));   //查询teamno报名有几条，邀请别人应该只有一条
        if(ObjectUtils.isNotEmpty(competitionApplies)){
            if(competitionApplies.size()==1) {
                CompetitionApply competitionApply2 = competitionApplies.get(0);
                if (competitionApply2.getApplyType() == 5) {
//                List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>().in(User::getId, applyAcceptValidate.getMemberId(), competitionApply2.getMemberId()).groupBy(User::getSex));
                    List<Member> members = memberMapper.selectList(new LambdaQueryWrapper<Member>().eq(Member::getId, competitionApply2.getMemberId()).groupBy(Member::getSex));
                    if (CollectionUtils.isNotEmpty(members) && members.size() == 1) {
                        Member member = members.get(0);
                        Member member1 = memberMapper.selectById(applyAcceptValidate.getMemberId());
                        if(member.getSex()==member1.getSex()){
                            throw new BaseException(0, "男女混打类型不匹配", 1);
                        }
                        CompetitionApply competitionApply = new CompetitionApply();  //生成邀请方的报名对象，插入数据库
                        BeanUtils.copyProperties(competitionApply2, competitionApply);
                        competitionApply.setId(null);
                        competitionApply.setMemberId(applyAcceptValidate.getMemberId());
                        competitionApply.setStatus(1);
                        competitionApply.setCreateTime(System.currentTimeMillis() / 1000);
                        competitionApply.setCreateId(applyAcceptValidate.getMemberId());
                        boolean exists = competitionApplyMapper.exists(new LambdaQueryWrapper<CompetitionApply>()   //插入前判断邀请方是否被邀请过
                                .eq(CompetitionApply::getCompetitionId, competitionApply.getCompetitionId())
                                .eq(CompetitionApply::getApplyType, competitionApply2.getApplyType())
                                .eq(CompetitionApply::getTeamNo, applyAcceptValidate.getTeamNo())
                                .eq(CompetitionApply::getMemberId, applyAcceptValidate.getMemberId()));
                        if (!exists) {                     //没有邀请过则进行数据库插入，并更新组队报名申请为成功
                            competitionApplyMapper.insert(competitionApply);
                            CompetitionApply competitionApply1 = new CompetitionApply();
                            competitionApply1.setId(competitionApply2.getId());
                            competitionApply1.setStatus(1);
                            competitionApplyMapper.updateById(competitionApply1);
                        }
                    } else {
                        //男女混打类型不匹配
                        throw new BaseException(0, "男女混打类型不匹配", 1);
                    }
                } else {
//                List<User> users = userMapper.selectList(new LambdaQueryWrapper<User>()
//                        .in(User::getId, applyAcceptValidate.getUserId(), competitionApply2.getUserId())
//                                .eq(User::getSex,competitionApply2.getApplyType()==2?1:0)
//                        .groupBy(User::getSex));
                    List<Member> members = memberMapper.selectList(new LambdaQueryWrapper<Member>()
                            .in(Member::getId, applyAcceptValidate.getMemberId(), competitionApply2.getMemberId())
                            .eq(Member::getSex, competitionApply2.getApplyType() == 2 ? 1 : 0)
                            .groupBy(Member::getSex));
                    if (CollectionUtils.isNotEmpty(members) && members.size() == 1) {
                        CompetitionApply competitionApply = new CompetitionApply();
                        BeanUtils.copyProperties(competitionApply2, competitionApply);
                        competitionApply.setId(null);
                        competitionApply.setMemberId(applyAcceptValidate.getMemberId());
                        competitionApply.setStatus(1);
                        competitionApply.setCreateTime(System.currentTimeMillis() / 1000);
                        competitionApply.setCreateId(applyAcceptValidate.getUserId());
                        boolean exists = competitionApplyMapper.exists(new LambdaQueryWrapper<CompetitionApply>()
                                .eq(CompetitionApply::getCompetitionId, competitionApply.getCompetitionId())
                                .eq(CompetitionApply::getApplyType, competitionApply2.getApplyType())
                                .eq(CompetitionApply::getMemberId, applyAcceptValidate.getUserId()));
                        if (!exists) {
                            competitionApplyMapper.insert(competitionApply);
                            CompetitionApply competitionApply1 = new CompetitionApply();
                            competitionApply1.setId(competitionApply2.getId());
                            competitionApply1.setStatus(1);
                            competitionApplyMapper.updateById(competitionApply1);
                        }
                    } else {
                        //男双打/女双打类型不匹配
                        if (competitionApply2.getApplyType() == 2) {
                            throw new BaseException(0, "男双打类型不匹配", 1);
                        } else if (competitionApply2.getApplyType() == 4) {
                            throw new BaseException(0, "女双打类型不匹配", 1);
                        }

                    }
                }
            }else{
                throw new BaseException(1,"已拒绝邀请",1);
            }
        }else{
            throw new BaseException(0,"邀请不符合",1);
        }

    }

    @Override
    public CompetitionShowVo applyShow(Integer memberId,Integer id) {
        MPJQueryWrapper<CompetitionApply> queryWrapper = new MPJQueryWrapper<>();
        queryWrapper
                .select("id as competitionId," +
                        "max(case when apply_type = 1 then '1' else '0' end) as nanOne," +
                        "max(case when apply_type = 2 then '1' else '0' end) as nanTwo," +
                        "max(case when apply_type = 3 then '1' else '0' end) as nvOne," +
                        "max(case when apply_type = 4 then '1' else '0' end) as nvTwo," +
                        "max(case when apply_type = 5 then '1' else '0' end) as allTwo")
                .notIn("status",2,5)
                .groupBy("competition_id")
                .orderByDesc("competition_id");
        Map<String,Object> param = new HashMap<>();
        param.put("memberId",memberId);
        param.put("id",id);

        competitionApplyMapper.setSearch(queryWrapper, param, new String[]{
                "=:memberId@member_id:int",
                "=:id@competition_id:int"
        });
        CompetitionShowVo invite = competitionApplyMapper.selectJoinOne(
                CompetitionShowVo.class,
                queryWrapper);
        return invite;
    }

    @Override
    public CompetitionSessionListedVo session(CompetitionSessionValidate sessionValidate) {
        Competition competition = competitionMapper.selectById(sessionValidate.getId());
        CompetitionSessionListedVo competitionSessionListedVo = new CompetitionSessionListedVo();
        List<CompetitionMatch> competitionMatches1 = competitionMapper.selectMatchList(competition.getId(),null,competition.getSchedule());
        if(CollectionUtils.isNotEmpty(competitionMatches1)){
            competitionMatches1.stream().forEach(f->{
                if(f.getPlayType()==1){
                    if(CollectionUtils.isNotEmpty(competitionSessionListedVo.getPlayTypeOne())){
                        competitionSessionListedVo.getPlayTypeOne().add(f);
                    }else{
                        competitionSessionListedVo.setPlayTypeOne(new ArrayList<>());
                        competitionSessionListedVo.getPlayTypeOne().add(f);
                    }
                }else if(f.getPlayType()==2){
                    if(CollectionUtils.isNotEmpty(competitionSessionListedVo.getPlayTypeTwo())){
                        competitionSessionListedVo.getPlayTypeTwo().add(f);
                    }else{
                        competitionSessionListedVo.setPlayTypeTwo(new ArrayList<>());
                        competitionSessionListedVo.getPlayTypeTwo().add(f);
                    }
                }else if(f.getPlayType()==3){
                    if(CollectionUtils.isNotEmpty(competitionSessionListedVo.getPlayTypeThree())){
                        competitionSessionListedVo.getPlayTypeThree().add(f);
                    }else{
                        competitionSessionListedVo.setPlayTypeThree(new ArrayList<>());
                        competitionSessionListedVo.getPlayTypeThree().add(f);
                    }
                }else if(f.getPlayType()==4){
                    if(CollectionUtils.isNotEmpty(competitionSessionListedVo.getPlayTypeFour())){
                        competitionSessionListedVo.getPlayTypeFour().add(f);
                    }else{
                        competitionSessionListedVo.setPlayTypeFour(new ArrayList<>());
                        competitionSessionListedVo.getPlayTypeFour().add(f);
                    }
                }else if(f.getPlayType()==5){
                    if(CollectionUtils.isNotEmpty(competitionSessionListedVo.getPlayTypeFive())){
                        competitionSessionListedVo.getPlayTypeFive().add(f);
                    }else{
                        competitionSessionListedVo.setPlayTypeFive(new ArrayList<>());
                        competitionSessionListedVo.getPlayTypeFive().add(f);
                    }
                }
            });
        }

        LambdaQueryWrapper<CompetitionSite> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CompetitionSite::getCompetitionId,competition.getId())
                .eq(CompetitionSite::getSchedule,competition.getSchedule());
        List<CompetitionSite> competitionSites = competitionSiteMapper.selectList(queryWrapper);
        if(CollectionUtils.isNotEmpty(competitionSites)){
            competitionSites.stream().forEach(f->{
                if(f.getPlayType()==1){
                    competitionSessionListedVo.setPlayAddressOne(f);
                }else if(f.getPlayType()==2){
                    competitionSessionListedVo.setPlayAddressTwo(f);
                }else if(f.getPlayType()==3){
                    competitionSessionListedVo.setPlayAddressThree(f);
                }else if(f.getPlayType()==4){
                    competitionSessionListedVo.setPlayAddressFour(f);
                }else if(f.getPlayType()==5){
                    competitionSessionListedVo.setPlayAddressFive(f);
                }
            });
        }
        return competitionSessionListedVo;
    }

    @Override
    public CompetitionPlayVo play(Integer id,Integer matchId) {
        CompetitionPlayVo play = new CompetitionPlayVo();
        List<Map> maps = competitionMapper.selectCompetitionUserInfo(id, matchId);
        if(CollectionUtils.isNotEmpty(maps)){
            maps.stream().forEach(f->{
                Integer teamTeype = (Integer) f.get("teamType");
                if(teamTeype==1){
                    play.setPlayerOneOrgName((String) f.get("orgName"));
                    play.setPlayerOneLogo((String) f.get("logo"));
                    play.setPlayerOne((String) f.get("teamName"));
                    play.setPlayerOneTotalScore(f.get("totalScore").toString());
                    play.setPlayerOneNo(f.get("teamNo").toString());
                }else if(teamTeype==2){
                    play.setPlayerTwoOrgName((String) f.get("orgName"));
                    play.setPlayerTwoLogo((String) f.get("logo"));
                    play.setPlayerTwo((String) f.get("teamName"));
                    play.setPlayerTwoTotalScore((f.get("totalScore").toString()));
                    play.setPlayerTwoNo(f.get("teamNo").toString());
                }
            });
        }
        List<Map> maps1 = competitionMapper.selectCompetitionRound(id, matchId);
        if(CollectionUtils.isNotEmpty(maps1)){
            maps1.stream().forEach(f->{
                Integer scoreNo = (Integer) f.get("scoreNo");
                if(scoreNo==1){
                    play.setPlayerOneOneScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoOneScore(f.get("playTwoTotal").toString());
                }else if(scoreNo==2){
                    play.setPlayerOneTwoScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoTwoScore(f.get("playTwoTotal").toString());
                }else if(scoreNo==3){
                    play.setPlayerOneThreeScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoThreeScore(f.get("playTwoTotal").toString());
                }else if(scoreNo==4){
                    play.setPlayerOneFourScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoFourScore(f.get("playTwoTotal").toString());
                }else if(scoreNo==5){
                    play.setPlayerOneFiveScore(f.get("playOneTotal").toString());
                    play.setPlayerTwoFiveScore(f.get("playTwoTotal").toString());
                }
            });
        }
        List<CompetitionScore> competitionScores = competitionScoreMapper.selectList(new LambdaQueryWrapper<CompetitionScore>().eq(CompetitionScore::getMatchId, matchId));
        if(CollectionUtils.isNotEmpty(competitionScores)){
            play.setRoundList(competitionScores);
        }else{
            play.setRoundList(new ArrayList<>());
        }
        CompetitionMatch competitionMatch = competitionMatchMapper.selectById(matchId);
        Competition competition = competitionMapper.selectById(id);
        CompetitionRule rule = competitionRuleMapper.selectOne(new LambdaUpdateWrapper<CompetitionRule>().eq(CompetitionRule::getCompetitionId, competitionMatch.getCompetitionId()).eq(CompetitionRule::getSchedule, competitionMatch.getSchedule()));
        play.setStartTime(competitionMatch.getStartTime());
        play.setStatus(competitionMatch.getStatus());
        play.setOrderNum(competitionMatch.getOrderNum());
        play.setCompetitionName(competition.getName());
        play.setSchedule(competition.getSchedule());
        play.setResult(competitionMatch.getResult());
        CompetitionSite competitionSite = competitionSiteMapper.selectOne(new LambdaQueryWrapper<CompetitionSite>()
                .eq(CompetitionSite::getCompetitionId, id)
                .eq(CompetitionSite::getPlayType, competitionMatch.getPlayType())
                .eq(ObjectUtils.isNotEmpty(competitionMatch.getSiteId()),CompetitionSite::getId,competitionMatch.getSiteId())
        );
        play.setPlayAddress(competitionSite.getAddress());
        play.setPlayAddressName(competitionSite.getName());
        play.setPlayScore(rule.getScoreType());
        return play;
    }

    @Override
    public CompetitionMatchDetail playDetail(Integer matchId) {
        return competitionMatchDetailMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchDetail>().eq(CompetitionMatchDetail::getMatchId,matchId));
    }

    @Override
    public PageResult<Map> scheduleList(PageValidate pageValidate, CompetitionScheduleSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();
        Map<String, Object> param = BeanMapUtils.create(searchValidate);
        IPage<Map> iPage = competitionMapper.selectscheduleList(new Page<>(page, limit),param);
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }
    @Override
    public PageResult<Map> scoreList(PageValidate pageValidate, CompetitionScoreSearchValidate searchValidate) {
        Integer page  = pageValidate.getPage_no();
        Integer limit = pageValidate.getPage_size();
        Map<String, Object> param = BeanMapUtils.create(searchValidate);
        IPage<Map> iPage = competitionMapper.selectScorelist(new Page<>(page, limit),param);
        return PageResult.iPageHandle(iPage.getTotal(), iPage.getCurrent(), iPage.getSize(), iPage.getRecords());
    }

    @Override
    public void playScoreAdd(CompetitionScore updateValidate) throws NoSuchFieldException, IllegalAccessException {
        Integer oneCount = 0;
        Integer twoCount = 0;
        for (int i = 0; i < 60; i++) {
            String fieldName = "round"+(i+1);
            Field field = CompetitionScore.class.getDeclaredField(fieldName);
            // 设置可访问私有字段
            field.setAccessible(true);
            // 获取字段的值
            if(field.get(updateValidate)!=null) {
                Integer value = (Integer) field.get(updateValidate);
                if (value == 1) {
                    oneCount = oneCount + 1;
                } else if (value == 2) {
                    twoCount = twoCount + 1;
                }
            }
        }
        CompetitionMatch match = competitionMatchMapper.selectById(updateValidate.getMatchId());
        CompetitionRule rule = competitionRuleMapper.selectOne(new LambdaUpdateWrapper<CompetitionRule>().eq(CompetitionRule::getCompetitionId, match.getCompetitionId()).eq(CompetitionRule::getSchedule, match.getSchedule()));
        int i = judgeSingleSet(oneCount, twoCount, rule.getScoreType());
        CompetitionMatchTeam competitionMatchTeam = competitionMatchTeamMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, updateValidate.getMatchId()).eq(CompetitionMatchTeam::getTeamType, i));
        if(ObjectUtils.isNotEmpty(competitionMatchTeam)){
            updateValidate.setWinTeamNo(competitionMatchTeam.getTeamNo());
        }
        updateValidate.setPlayOneTotal(oneCount);
        updateValidate.setPlayTwoTotal(twoCount);
        if(ObjectUtils.isNotEmpty(updateValidate.getScoreId())){
            competitionScoreMapper.updateById(updateValidate);
        }else{
            competitionScoreMapper.insert(updateValidate);
        }
        List<CompetitionScore> competitionScores = competitionScoreMapper.selectList(new LambdaUpdateWrapper<CompetitionScore>().eq(CompetitionScore::getMatchId, updateValidate.getMatchId()));
        JSONObject json = judgeMatch(competitionScores,Integer.parseInt(rule.getRoundCount()),Integer.parseInt(rule.getVictoryCount()));
        if(json!=null){
            Integer winTeam = json.getInteger("winTeam");
            if(winTeam>0) {
                CompetitionMatchTeam team = competitionMatchTeamMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, updateValidate.getMatchId()).eq(CompetitionMatchTeam::getTeamType, winTeam));
                Integer wonByA = json.getInteger("wonByA");
                Integer wonByB = json.getInteger("wonByB");
                CompetitionMatch competitionMatch = new CompetitionMatch();
                competitionMatch.setPlayOneScore(wonByA);
                competitionMatch.setPlayTwoScore(wonByB);
                competitionMatch.setResult(team.getTeamNo());
                competitionMatch.setStatus(1);
                competitionMatch.setId(updateValidate.getMatchId());
                competitionMatchMapper.updateById(competitionMatch);
                CompetitionMatchTeam teamUpdate = new CompetitionMatchTeam();
                teamUpdate.setStatus(1);
                competitionMatchTeamMapper.update(teamUpdate, new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, team.getMatchId()).eq(CompetitionMatchTeam::getTeamNo, team.getTeamNo()));
            }
            Integer lostTeam = json.getInteger("lostTeam");
            if(lostTeam>0){
                CompetitionMatchTeam team = competitionMatchTeamMapper.selectOne(new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, updateValidate.getMatchId()).eq(CompetitionMatchTeam::getTeamType, lostTeam));
                CompetitionMatchTeam teamUpdate = new CompetitionMatchTeam();
                teamUpdate.setStatus(2);
                competitionMatchTeamMapper.update(teamUpdate, new LambdaUpdateWrapper<CompetitionMatchTeam>().eq(CompetitionMatchTeam::getMatchId, team.getMatchId()).eq(CompetitionMatchTeam::getTeamNo, team.getTeamNo()));

            }
        }
    }

    // 判断一局比赛的胜负
    private static int judgeSingleSet(int scoreA, int scoreB, int winScore) {
        // 校验比分数据是否合法
        if (scoreA < 0 || scoreB < 0) {
            throw new IllegalArgumentException("比分不能为负数");
        }

        // 校验是否有一方达到胜利条件
        if (scoreA < winScore && scoreB < winScore) {
            throw new IllegalArgumentException("双方均未达到胜利分数");
        }

        // 校验是否存在分差不足2分的无效高分情况
        if (Math.abs(scoreA - scoreB) < 2) {
            if (scoreA > winScore || scoreB > winScore) {
                throw new IllegalArgumentException("分差不足2分时不能出现超过胜利分数的情况");
            }
        }
        if (scoreA >= winScore && scoreA - scoreB >= 2) {
            return 1;
        } else if (scoreB >= winScore && scoreB - scoreA >= 2) {
            return 2;
        } else if (scoreA >= winScore - 1 && scoreB >= winScore - 1) {
            if (scoreA > scoreB) {
                return 1;
            } else if (scoreB > scoreA) {
                return 2;
            }
        }
        return 0;
    }

    // 比赛局数
    private static final int MAX_SETS = 3;

    // 判断整场比赛的胜负
    public static JSONObject judgeMatch(List<CompetitionScore> competitionScores,Integer roundCount,Integer victoryCount) {
        JSONObject jsonObject = new JSONObject();
        if(CollectionUtils.isNotEmpty(competitionScores)) {
            int setsWonByA = 0;
            int setsWonByB = 0;
            int winTeam = 0;
            int lostTeam = 0;
            for (CompetitionScore setScore : competitionScores) {
                int winner = judgeSingleSet(setScore.getPlayOneTotal(), setScore.getPlayTwoTotal(), 21);
                if (winner == 1) {
                    setsWonByA++;
                } else if (winner == 2) {
                    setsWonByB++;
                }
            }
            if (setsWonByA >= roundCount / victoryCount + 1) {
                winTeam = 1;
                lostTeam = 2;
            } else if (setsWonByB >= roundCount / victoryCount + 1) {
                lostTeam = 1;
                winTeam = 2;
            }
            jsonObject.put("wonByA",setsWonByA);
            jsonObject.put("wonByB",setsWonByB);
            jsonObject.put("winTeam",winTeam);
            jsonObject.put("lostTeam",lostTeam);

        }
        return jsonObject;
    }
}
